//
//  KDMonitorBodyView.m
//  PublicSentimentMonitorSystem
//
//  Created by 魏强 on 15/10/29.
//  Copyright © 2015年 魏强. All rights reserved.
//

#import "KDMonitorBodyView.h"
#import "KDMListCell.h"
#import "KDMListCellBaseModel.h"
#import "KDBaesMonitorModel.h"
#import "KDMKeywordMonitorResult.h"
#import "KDWebMonitorResult.h"
#import "KDWeiboMonitorResult.h"

#import "KDGetKeywordListParam.h"
#import "KDMGetWebListParam.h"
#import "KDGetAuthorListParam.h"
#import "KDGetWeiboListParam.h"
#import "KDMGetWebListParam.h"
#import "KDMonitorRequestTool.h"
#import "KDGetAppListParam.h"
#import "KDMBaseBoard.h"
#import "KDMBaseBoardModel.h"
#import "GBAddFriendAnimation.h"

#define Cell_H 120
#define BTN_WIDTH 75
#define BTN_WIDTH2 screenW / 4 //app的二级菜单的按钮高度
#define SETBTN_WIDTH 36
@interface KDMonitorBodyView ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate, KDMListCellDelegate, ButtonClickToController, KDMBaseboardDelegate>
{
    
}
/** 右边弹出的选择界面*/
@property (nonatomic, weak) KDMBaseBoard *baseView;
/** 右边弹出的选择界面的遮盖*/
@property (nonatomic, weak) UIButton *cover;
@property (nonatomic, weak) UIScrollView *detailScrollView;
@property (nonatomic, weak) UIButton *selectDetailBtn;
@property (nonatomic, weak) UIScrollView *bodyScrollView;
/** 当前显示的tableView*/
@property (nonatomic, weak) UITableView *currentTabV;
/** 当前的baseBoardModel*/
@property (nonatomic, strong) KDMBaseBoardModel *baseBoardModel;
/** 默认的baseBoardModel*/
@property (nonatomic, strong) KDMBaseBoardModel * defaultBaseBoardModel;

/**
 * tableView的model的数据*
 */
@property (nonatomic, strong) NSDictionary *dataDic;
/**
 *  加载第几页
 */
@property (nonatomic, strong) NSString *page;
/**
 *  所有的列表数据
 */
@property (nonatomic, strong) NSArray *infoArr;
/**
 *  装所有主题model的arr
 */
@property (nonatomic, strong) NSArray *themeArr;
@property (nonatomic, strong) NSDateFormatter *fmt;
/**
 *  没有数据时的提示
 */
@property (nonatomic, weak) UIView * notice;
/**
 *  头部scrollView旁边的设置按钮
 */
@property (nonatomic, weak) UIButton *setBtn;
/**
 *  当前属于第几个
 */
@property (nonatomic, copy) NSString *currentIndex;
@end
@implementation KDMonitorBodyView
@synthesize  baseBoardModel = _baseBoardModel;
@synthesize themeArr = _themeArr;
#pragma mark - 懒加载区
- (NSDateFormatter *)fmt
{
    if (!_fmt) {
        _fmt = [[NSDateFormatter alloc]init];
        _fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];;
        _fmt.dateFormat = @"yyyy-MM-dd";
    }
    return _fmt;
}
- (NSDictionary *)dataDic
{
    if (!_dataDic) {
        _dataDic = [NSDictionary dictionary];
    }
    return _dataDic;
}
- (NSString *)page
{
    if (!_page) {
        _page = @"1";
    }
    return _page;
}
- (NSArray *)themeArr
{
    if (!_themeArr) {
        _themeArr = [NSArray new];
    }
    return _themeArr;
}
- (void)setThemeArr:(NSArray *)themeArr{
    if (!themeArr) {
        return;
    }
    _themeArr = themeArr;
    self.currentIndex = @"0";
    if (self.model.mainType == 3) {
        [self setUpHeadScrollViewWithoutSetUpBtn];
    }else{
        [self setUpHeadScrollView];
    }
}
- (NSArray *)infoArr
{
    if (!_infoArr) {
        _infoArr = [NSArray new];
    }
    return _infoArr;
}
- (KDMBaseBoardModel *)baseBoardModel
{
    if (!_baseBoardModel) {//那里找不到了，就自己建
        _baseBoardModel = [[KDMBaseBoardModel alloc]init];
        _baseBoardModel.webSrcType = @"0";
//        NSDate *newdate = [[NSDate date] initWithTimeInterval:- (24 *60 * 60 * 6 )sinceDate:[NSDate date]];
        _baseBoardModel.startTime = @"1970-01-01";//[self.fmt stringFromDate:newdate];
        _baseBoardModel.endTime = @"";
        _baseBoardModel.timeIndex = @"9";
        _baseBoardModel.docType = @"0";
        _baseBoardModel.bussiness = @"0";
        if (self.model.mainType == 3) {
            if (self.model.showReginType == 0) {
                _baseBoardModel.regionType = 4;
            }else{
                _baseBoardModel.regionType = self.model.showReginType;
            }
        }
        self.defaultBaseBoardModel = _baseBoardModel ;
    }
    return _baseBoardModel;
}
- (void)setModel:(KDMBodyViewModel *)model{
    _model = model;
    self.themeArr = model.infoArr;
    
}
- (void)setSelectDetailBtn:(UIButton *)selectDetailBtn
{
    _selectDetailBtn.selected = NO;
    _selectDetailBtn = selectDetailBtn;
    _selectDetailBtn.selected = YES;
}
+ (instancetype)bodyViewWithFrame:(CGRect)frame{
    return [[self alloc]initWithFrame:frame];
}
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor =BackGroundColor;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(KDMonitorControllerTopBtnClick:) name:@"KDMonitorControllerTopicBtnDidClickNotyfication" object:nil];
    }
    return self;
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - 板块布置区
/***  创建头部scrollView */
- (void)setUpHeadScrollView
{
    if (!self.detailScrollView) {
        UIScrollView *scr = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, screenW - SETBTN_WIDTH, 44 -10)];
        self.detailScrollView = scr;
        scr.delegate = self;
        scr.contentSize = CGSizeMake(BTN_WIDTH * self.themeArr.count, 1);
        scr.showsHorizontalScrollIndicator = NO;
        scr.showsVerticalScrollIndicator = NO;
        scr.backgroundColor = [UIColor whiteColor];
        [self addSubview:scr];
    }
    
    [self setUpBtn];
    [self setUpSetBtn];
    [self setUpBodyScrollView];
//    [self getFakeData];
    
}
/**
 *  如果是不需要设置按钮的scrollView,就用这个
 */
- (void)setUpHeadScrollViewWithoutSetUpBtn{
    if (!self.detailScrollView) {
        UIScrollView *scr = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0,  screenW - SETBTN_WIDTH, 44 -10)];
        self.detailScrollView = scr;
        scr.delegate = self;
        scr.contentSize = CGSizeMake(BTN_WIDTH2 * self.themeArr.count, 1);
        scr.showsHorizontalScrollIndicator = NO;
        scr.showsVerticalScrollIndicator = NO;
        scr.backgroundColor = [UIColor whiteColor];
        [self addSubview:scr];
    }
    [self setUpBtn];
    [self setUpSetBtn];
    [self setUpBodyScrollView];
}
/***  创建装tableView的scrollView */
- (void)setUpBodyScrollView
{
    if (!self.bodyScrollView) {
        UIScrollView * bodyScrollView = [[UIScrollView alloc]init];
        self.bodyScrollView = bodyScrollView;
        bodyScrollView.frame = CGRectMake(0, CGRectGetMaxY(self.detailScrollView.frame), screenW, screenH - CGRectGetMaxY(self.detailScrollView.frame)-49);
        bodyScrollView.delegate = self;
        bodyScrollView.contentSize = CGSizeMake(screenW * self.themeArr.count, 1);
        bodyScrollView.showsHorizontalScrollIndicator = YES;
        bodyScrollView.pagingEnabled = YES;
        bodyScrollView.scrollEnabled = YES;
//        bodyScrollView.showsVerticalScrollIndicator = YES;
        [self addSubview:bodyScrollView];
        //初始化主题
        [self setUpTableView];

    }
}
/***  各大主题tableView的设置*/
- (void)setUpTableView
{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0  , 0, screenW, self.bodyScrollView.height  - 64) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tag = 1000;
    tableView.tableFooterView = [UIView new];
    tableView.separatorColor = BackGroundColor;
    tableView.backgroundColor = BackGroundColor;
    tableView.rowHeight = Cell_H;
    if (!iOS7) {
        tableView.estimatedRowHeight = Cell_H;
    }
    self.currentTabV = tableView;
    [self.bodyScrollView addSubview:tableView];
    tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    // 设置footer
    self.currentTabV.footer = footer;
    [self.currentTabV.header beginRefreshing];
}
- (void)setUpBtn{
    for (id btn in self.detailScrollView.subviews) {
        if ([btn isKindOfClass:[UIButton class]]) {
            [btn removeFromSuperview];
        }
    }
    for (int i = 0; i < self.themeArr.count; i++) {
        KDBaesMonitorModel *model = self.themeArr[i];

        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        CGRect labelRect = [model.m_Name boundingRectWithSize:CGSizeMake(screenW, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
        //        KDLog(@"%@",NSStringFromCGRect(labelRect));
        if (self.themeArr.count <= 1) {//如果小于4个，就平分
            btn.width = (screenW - SETBTN_WIDTH)/(self.themeArr.count *1.0);
        }else{
            btn.width = labelRect.size.width +10;
        }
        
        btn.height = self.detailScrollView.height -10;
        if (i == 0) {
            btn.x = 10;
        }else{
            UIButton *tempBtn = (UIButton *)[self.detailScrollView viewWithTag:100 + i -1];
            btn.x = CGRectGetMaxX(tempBtn.frame) +10;
        }
        btn.y = 5;
        btn.tag = 100+i;
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        UIImage *image2 = [UIImage imageNamed:@"btn_background"];
        CGFloat top = 0; // 顶端盖高度
        CGFloat bottom = 0 ; // 底端盖高度
        CGFloat left = 15; // 左端盖宽度
        CGFloat right = 15; // 右端盖宽度
        UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
        image2 = [image2 resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
        [btn setBackgroundImage:image2 forState:UIControlStateNormal];
//
        [btn setBackgroundImage:image2 forState:UIControlStateSelected];
        btn.titleLabel.layer.cornerRadius = 5;
        btn.titleLabel.clipsToBounds = YES;
        [btn setTitle:model.m_Name forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(detailBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitleColor: WQColor(149, 149, 149) forState:UIControlStateNormal];
        [btn setTitleColor:WQColor(85, 196, 95) forState:UIControlStateSelected];
        //        btn.backgroundColor = WQColor(249, 249, 249);
        //        btn.tintColor = KDColor;
        if (btn.tag == 100) {
            self.selectDetailBtn = btn;
        }
        [self.detailScrollView addSubview:btn];
    }
    UIButton *btn = (UIButton *)[self.detailScrollView viewWithTag:99+self.self.themeArr.count];
    self.detailScrollView.contentSize = CGSizeMake(CGRectGetMaxX(btn.frame), 1);
}
- (void)setUpSetBtn{
    UIButton *setBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.setBtn = setBtn;
    setBtn.width = SETBTN_WIDTH;
    setBtn.height = setBtn.width;
    setBtn.x = screenW - SETBTN_WIDTH;
    setBtn.centerY = self.detailScrollView.centerY;
//    KDLog(@"%@", NSStringFromCGRect(setBtn.frame));
    setBtn.backgroundColor = [UIColor whiteColor];
    [setBtn addTarget:self action:@selector(setBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:setBtn];
    if (self.model.mainType == 3) {//如果是app进来
        [setBtn setImage:[UIImage imageNamed:@"筛选黑"] forState:UIControlStateNormal];
    }else{
        [setBtn setImage:[UIImage imageNamed:@"添加右滑上报按钮"] forState:UIControlStateNormal];

    }
    
   
    
}
- (void)setUpNotise{
    UIView * notice = [[UIView alloc]initWithFrame:self.currentTabV.bounds];
    self.notice = notice;
    UILabel * noticeLb = [[UILabel alloc]initWithFrame:self.notice.bounds];
    notice.backgroundColor = BackGroundColor;
    notice.y = 0;
    noticeLb.centerY = noticeLb.height * 0.5;
    //    KDLog(@"%@", NSStringFromCGRect(notice.frame));
    noticeLb.text = @"暂时没有满足条件的数据";
    noticeLb.textColor = WQColor(178, 182, 184);
    noticeLb.textAlignment = NSTextAlignmentCenter;
    [notice addSubview:noticeLb];
    self.currentTabV.tableHeaderView = notice;
}
/***  设置右边选择页面*/
-(void)setUpRightChoosePage
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    if (!self.cover) {
        //加蒙板
        UIButton *cover = [[UIButton alloc]initWithFrame:window.bounds];
        self.cover = cover;
        cover.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
        
        [cover addTarget:self action:@selector(coverClick:) forControlEvents:UIControlEventTouchUpInside];
        [window addSubview:_cover];
    }
    self.cover.frame = window.bounds;
    //    KDLog/Users/MarkWei/Downloads/办理“深圳市重特大疾病补充医疗保险” 员工个人参保流程操作指引.doc(@"%@", NSStringFromCGRect(self.cover.frame));
    //创建底板
    if (!self.baseView) {
        KDMBaseBoard *baseView = [KDMBaseBoard baseboard];
        self.baseView = baseView;
        baseView.delegate = self;
        baseView.x = screenW;
        baseView.y = 64;
        baseView.height = screenH - baseView.y - 49 ;
        baseView.width = screenW - screenW*0.175;
        baseView.mainPageType = self.model.mainType;
        
        [_cover addSubview:baseView];
    }
        _baseView.showReginType = self.model.showReginType;
    //    _baseView.model.idstr = [NSString stringWithFormat:@"%ld", (long)self.currentBodyView.homeThemeModel.ID];
    //    _baseView.parentIdstr = [NSString stringWithFormat:@"%ld", (long)self.currentBodyView.model.ParentID];
    _baseView.height = screenH - _baseView.y - 49 ;
    _baseView.width = screenW - screenW*0.175;
    [UIView animateWithDuration:0.4 animations:^{
        _baseView.x = screenW*0.175;
    }];
}
#pragma mark - 事件点击区
/**
 *  二级菜单的按钮被点击了
 */
- (void)setBtnClick{
    if (self.model.mainType == 3) {
        if (!self.setBtn.selected) {
            //设置右边的选择页面
            [self setUpRightChoosePage];
        } else
        {
            [self coverClick:self.cover];
        }
        self.setBtn.selected = self.setBtn.selected;
    }else{
        GBAddFriendAnimation *weChatAddFriend = [[GBAddFriendAnimation alloc] initWithFrame:CGRectMake(screenW - 105, CGRectGetMaxY(self.detailScrollView.frame) +15, 100, 90)];
        weChatAddFriend.titleArray = @[@"筛选", @"设置"];
        weChatAddFriend.imageArray = @[@"监测筛选", @"监测设置"];
        weChatAddFriend.delegate1001 = self;
        [self addSubview:weChatAddFriend];
    }

    
}
/***  细节Btn被点击 */
-(void)detailBtnDidClick:(UIButton *)btn
{
    NSInteger num = btn.tag -100;
    [self.bodyScrollView setContentOffset:CGPointMake(screenW*num, self.bodyScrollView.contentOffset.y) animated:YES];
    [self.bodyScrollView scrollRectToVisible:CGRectMake(screenW * num, self.bodyScrollView.frame.origin.y, screenW, self.bodyScrollView.frame.size.height) animated:YES];
    //被点击的btn的后一个btn
    UIButton *btn1 = (UIButton *)[self.detailScrollView viewWithTag:num +101];
    UIButton *btn2 = (UIButton *)[self.detailScrollView viewWithTag:num +99];
    
    NSInteger i = self.selectDetailBtn.tag - btn.tag;
    float xx;
    if (i > 0) {//向左点
        xx = btn.x - btn2.width ;
    }else{//向右点
        xx = btn.x +btn1.width ;
    }
    self.selectDetailBtn.selected = NO;
    self.selectDetailBtn = btn;
    
    //    KDLog(@"%f",xx);
    [self.detailScrollView scrollRectToVisible:CGRectMake(xx, self.detailScrollView.y, btn.width, self.detailScrollView.height) animated:YES];
}
/***  去掉蒙板及右边页 */
- (void)coverClick:(UIButton *)cover
{
    [UIView animateWithDuration:0.4 animations:^{
        self.baseView.x = screenW;
        
    } completion:^(BOOL finished) {
        
        self.cover.frame = CGRectMake(0, 0, 0, 0);
//        self.rightBarBtn.selected = NO;
        
    }];
    
}
#pragma mark - 网络请求区
- (void)getFakeData
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"FakeData" ofType:@"plist"];
    //    NSArray *data = [[NSArray alloc] initWithContentsOfFile:plistPath];
    self.infoArr = [KDMListCellBaseModel objectArrayWithFile:plistPath];
    [self setUpBodyScrollView];
}
- (KDGetMonitorListParam *)requestMethod{
    KDGetMonitorListParam *param1;
    if (!self.themeArr.count) {//没有二级菜单，返回无数据
        [self setUpNotise];
        return nil;
    }
    //创建参数
    switch (self.model.mainType) {//
        case 0:{
            KDGetKeywordListParam *param = [[KDGetKeywordListParam alloc]init];
            param.method = @"getMonitorKeywordItemList";
            param.p = self.page;
            param.limit = @"20";
            param.kindType = self.baseBoardModel.webSrcType;
            param.startTime = self.baseBoardModel.startTime;
            param.endTime = self.baseBoardModel.endTime;
            param.property = self.baseBoardModel.docType;
            param.sortType = @"0";
            param.keyword = self.baseBoardModel.secondSearch;
            
            KDBaesMonitorModel *model = self.themeArr[self.currentIndex.integerValue];
            param.m_Id = model.m_Id ;
            param1 = param;
            break;
        }
        case 1:{
            
            KDMGetWebListParam *param = [[KDMGetWebListParam alloc]init];
            param.method = @"getMonitorWebSiteItemList";
            param.p = self.page;
            param.business = (self.baseBoardModel.bussiness.integerValue)?@"true":@"false";
            param.keyword = self.baseBoardModel.secondSearch;
            param.startTime = self.baseBoardModel.startTime;
            param.endTime = self.baseBoardModel.endTime;
            param.property = self.baseBoardModel.docType;//
            param.limit = @"20";
            
            KDBaesMonitorModel *model = self.themeArr[self.currentIndex.integerValue];
            param.wsm_id = model.m_Id ;
            param1 = param;
            break;
        }
        case 2:{
            KDGetAuthorListParam *param = [[KDGetAuthorListParam alloc]init];
            param.method = @"getMonitorAuthorItemList";
            param.startTime = self.baseBoardModel.startTime;
            param.endTime = self.baseBoardModel.endTime;
            param.property = self.baseBoardModel.docType;
            param.p = self.page;
            param.limit = @"20";
            param.keyword = self.baseBoardModel.secondSearch;
            param.kindType = self.baseBoardModel.webSrcType;
            param.sortType = @"0";
            KDBaesMonitorModel *model = self.themeArr[self.currentIndex.integerValue];
            param.a_id =  model.m_Id;
            param1 = param;
            break;
        }
        case 3:{
            KDGetAppListParam *param = [[KDGetAppListParam alloc]init];
            param.method = @"getMonitorAppItemList";
            param.p = self.page;
            param.limit = @"20";
            param.startTime = self.baseBoardModel.startTime;
            param.endTime = self.baseBoardModel.endTime;
//            param.property = self.baseBoardModel.docType;
            param.business = (self.baseBoardModel.bussiness.integerValue)?@"true":@"false";//待定
            param.keyword = self.baseBoardModel.secondSearch;
            param.property = self.baseBoardModel.docType;
            param.sortType = @"0";
            param.regionType = self.baseBoardModel.regionType;
            KDBaesMonitorModel *model = self.themeArr[self.currentIndex.integerValue];
            param.app_id =[NSString stringWithFormat:@"%ld", (long)model.m_Id] ;
            param1 = param;
            break;
        }
        default:
            break;
    }
    return param1;
}
- (void)loadData{
    [self.notice removeFromSuperview];
    self.currentTabV.tableHeaderView.height = 0;
    self.page = @"1";
    KDGetMonitorListParam *param = [self requestMethod];
    if (!param) {//如果没有子主题了就不要再请求了
        [self.currentTabV.header endRefreshing];
        return;
    }
    WS(ws);
    [KDMonitorRequestTool getMonitorListWithParam:param WithMainType:self.model.mainType success:^(KDMKeywordMonitorResult * responseObejct) {
        KDMKeywordMonitorResult *result = responseObejct;
        if ([result.status isEqualToString:@"notlogin"]) {//如果被别人强制登陆了
            //写提示“该账号已在别处登录”
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"该账号已在别处登录" message:@"请重新登录" delegate:ws cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [ws.currentTabV.header endRefreshing];
            
        }else{//正常情况下，就加载数据
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            if (!result.info) {
                [ws setUpNotise];
                [ws.currentTabV.header endRefreshing];
                return ;
            }
            
            [dic setObject:result.info forKey:ws.currentIndex];
            ws.dataDic = dic;
            ws.infoArr = result.info;
            if (ws.infoArr.count == 0) {
                [ws setUpNotise];
            }
            //设置page＝1，方便上拉加载时重新从第一页开始加载,
            
            ws.page = [NSString stringWithFormat:@"%ld",ws.page.integerValue +1];
            [ws.currentTabV reloadData];
            [ws.currentTabV.header endRefreshing];
            [ws.currentTabV.footer resetNoMoreData];
        }
        KDLog(@"%@", result.info);
    } failure:^(NSError *error) {
        [ws.currentTabV.header endRefreshing];
        KDLog(@"%@",error);
        UIAlertView *messageView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"数据请求失败，请检查网络" delegate:ws cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [messageView show];
    }];
}
- (void)loadMoreData{
    [self requestMethod];
    KDGetMonitorListParam *param = [self requestMethod];
    WS(ws);
    [KDMonitorRequestTool getMonitorListWithParam:param WithMainType:self.model.mainType success:^(KDMKeywordMonitorResult *responseObejct) {
        KDMKeywordMonitorResult *result = responseObejct;
        if ([result.status isEqualToString:@"notlogin"]) {//如果被别人强制登陆了
            //写提示“该账号已在别处登录”
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"该账号已在别处登录" message:@"请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [ws.currentTabV.header endRefreshing];
            
        }else{//正常情况下，就加载数据
            if (responseObejct.count <= ws.infoArr.count) {
                [ws.currentTabV.footer endRefreshing];
                return ;
            }
            NSMutableArray *arr = [NSMutableArray arrayWithArray:ws.infoArr];
            [arr addObjectsFromArray: result.info];
            ws.infoArr = arr;
            [ws.currentTabV reloadData];
            [ws.currentTabV.footer endRefreshing];
            if (responseObejct.count <= ws.infoArr.count) {
                [ws.currentTabV.footer endRefreshing];
            }
            //设置page++,
            ws.page = [NSString stringWithFormat:@"%ld",ws.page.integerValue +1];
            [ws.currentTabV reloadData];
            [ws.currentTabV.footer endRefreshing];
//            KDLog(@"%@", result.info);
        }
    } failure:^(NSError *error) {
        [ws.currentTabV.footer endRefreshing];
        KDLog(@"%@",error);
        UIAlertView *messageView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"数据请求失败，请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [messageView show];
    }];
}
#pragma mark - UIScrollViewDelegate
//scrollView滑动停止会调动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.bodyScrollView)
    {
        int num = (int)scrollView.contentOffset.x/screenW;
        UIButton *btn = (UIButton *)[self.detailScrollView viewWithTag:num +100];
        [self adjustFrameWithScrollView:scrollView];
        //判断向左滑还是向右滑
        NSInteger i = self.selectDetailBtn.tag - btn.tag;
        self.selectDetailBtn.selected = NO;
//        CGFloat selectBtn_W = btn.width;
//        CGFloat disSelectBtn_w = self.selectDetailBtn.width;
        self.selectDetailBtn = btn;
        float xx;
        if (i > 0) {//<----
            xx = btn.x - btn.width; ;
            
        }else{//--->
            xx = btn.x + btn.width;;
        }
        
        //移动detailScrollView
        [self.detailScrollView scrollRectToVisible:CGRectMake(xx, self.detailScrollView.y, btn.width, self.detailScrollView.height) animated:YES];
    }
}
/***  当scrollView自动停止的时候会调用（不包括手抓的）*/
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    if (scrollView == self.bodyScrollView)
    {
        [self adjustFrameWithScrollView:scrollView];
    }
}

/***  重新确认CurrentTableView */
- (void)adjustFrameWithScrollView:(UIScrollView *)scrollView
{
    //    WS(ws);
    //防止没刷完之前就切换后一直刷的bug
    [self.currentTabV.header endRefreshing];
    NSUInteger num = (NSUInteger)scrollView.contentOffset.x/screenW;
    
    self.currentIndex = [NSString stringWithFormat:@"%ld", num];
    self.currentTabV = (UITableView *)[self.bodyScrollView viewWithTag:1000+num];
//    self.homeThemeModel = self.themeArr[num];
    if (!self.currentTabV) { //划到这页，判断这页有无tableView，没有的话就建一个
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(screenW *num , 0, screenW, self.bodyScrollView.height - 64) style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tag = num + 1000;
        tableView.tableFooterView = [UIView new];
        tableView.backgroundColor = BackGroundColor;
        tableView.separatorColor = BackGroundColor;
        tableView.rowHeight = Cell_H;
        if (!iOS7) {
            tableView.estimatedRowHeight = Cell_H;
        }
        [self.bodyScrollView addSubview:tableView];
        tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
        MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        [footer setTitle:@"" forState:MJRefreshStateIdle];
        tableView.footer = footer;
        self.currentTabV = tableView;
    }
    self.baseBoardModel = self.defaultBaseBoardModel;
    [self.currentTabV.header beginRefreshing];
    self.infoArr = self.dataDic[self.currentIndex];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return self.infoArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KDMListCell *cell = [KDMListCell cellWithTableView:tableView andVersion:self.model.version];
    //    KDLog(@"waimian%d", indexPath.row);
    cell.delegate = self;
    if (tableView == self.currentTabV)
    {
        cell.delegate = self;
        if (self.infoArr.count != 0)
        {
            cell.model = self.infoArr[indexPath.row];
        }
        return cell;
    }else{
        return cell;
    }
}
/**
 *  cell被点击了
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.currentTabV) {
        if (_delegate && [_delegate respondsToSelector:@selector(KDMonitorBodyView:WithKDMListCellBaseModel:didSelectRowAtIndexPath:)]) {
            if (self.infoArr.count == 0) {
                return;
            }
            KDMListCell *cell = (KDMListCell *)[tableView cellForRowAtIndexPath:indexPath];
            cell.highlight = YES;
            NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
            [arr replaceObjectAtIndex:indexPath.row withObject:cell.model];
            self.infoArr = arr;
            KDMListCellBaseModel *model = self.infoArr[indexPath.row];
            [_delegate KDMonitorBodyView:self WithKDMListCellBaseModel:model didSelectRowAtIndexPath:indexPath];
        }
    }
}



#pragma mark - KDMListCellDelegate
/**
 *  上报按钮被点击了
 */
- (void)KDMListCell:(KDMListCell *)cell reportBtnClick:(UIButton *)reportBtn{
    if (_delegate &&[_delegate respondsToSelector:@selector(KDMonitorBodyView:WithKDMListCellBaseModel:)]) {
        [_delegate KDMonitorBodyView:self WithKDMListCellBaseModel:cell.model];
    }
}

- (void)KDMListCell:(KDMListCell *)cell relationBtnClick:(UIButton *)relationBtn{
    if ( _delegate && [_delegate respondsToSelector:@selector(KDMonitorBodyView:relationBtnClickWithModel:)]) {
        [_delegate KDMonitorBodyView:self relationBtnClickWithModel:cell.model];
    }
}

- (void)KDMListCell:(KDMListCell *)cell collectBtnClick:(UIButton *)collectBtn{
    NSIndexPath *ip = [self.currentTabV indexPathForCell:cell];
    NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
    [arr replaceObjectAtIndex:ip.row withObject:cell.model];
    self.infoArr = arr;
}
#pragma mark - 通知接收区
//- (void)confirmBtnClick:(NSNotification *)noty{
//    
//    // 只接收一个bodyView界面的通知
//    KDMBaseBoardModel *model = noty.userInfo[@"baseBoardModel"];
//    NSInteger mainType = [noty.userInfo[@"parentId"] integerValue];
//    if (self.model.mainType == mainType) {
//        self.baseBoardModel = model;
//        [self.currentTabV.header beginRefreshing];
//    }
//    
//}
- (void)KDMonitorControllerTopBtnClick:(NSNotification *)noty{
    KDMonitorBodyView *bodyView = noty.userInfo[@"currentBodyView"];
    if (self == bodyView) {//还原为默认的那个model
        self.baseBoardModel = self.defaultBaseBoardModel;
        if (!self.currentTabV) {
            return;
        }
        [self.currentTabV.header beginRefreshing];
    }
}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView.title isEqualToString:@"该账号已在别处登录"]) {
        switch (buttonIndex) {
            case 0:
                if (_delegate && [_delegate respondsToSelector:@selector(bodyViewDidLoginedByOther:)]) {
                    [_delegate bodyViewDidLoginedByOther:self];
                }
                break;
            default:
                break;
        }
    }
}

#pragma mark - 仿微信界面按钮点击的代理
-(void)btnClickToController:(UIButton *)btn
{
    if ([btn.currentTitle isEqualToString:@"筛选"]) {
        if (!btn.selected) {
            
            //设置右边的选择页面
            [self setUpRightChoosePage];
        } else
        {
            [self coverClick:self.cover];
        }
        btn.selected = btn.selected;
    }else{//点中了设置按钮
        if (_delegate &&[_delegate respondsToSelector:@selector(KDMonitorBodyView:SetBtnClickWithKDMBodyViewModel:)]) {
            [_delegate KDMonitorBodyView:self SetBtnClickWithKDMBodyViewModel:self.model];
        }
    }
    
    
}

#pragma  mark - KDMBaseboardDelegate
/**
 *  确定按钮被点击了
 */
- (void)baseBoard:(KDMBaseBoard *)baseBoard
confirmBtnDidClickWithBaseBoardModel:(KDMBaseBoardModel *)model{
    self.baseBoardModel = model;
    [self.currentTabV.header beginRefreshing];
    [self coverClick:self.cover];
}
@end
